<template>
  <div class="app-container">
    <el-row :gutter="24" type="flex" justify="between" class="padding">
      <el-col :span="12" class="titles">
        <span class="title">企业认证配置</span>
      </el-col>
      <el-col :span="12" class="right">
        <el-button type="primary" size="medium" @click="handleAdd">新增企业认证配置</el-button>
      </el-col>
    </el-row>
    <el-table
      v-loading="listLoading"
      :data="list"
      row-key="id"
      border
      default-expand-all
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        prop="authCode"
        label="企业认证码"
      />
      <el-table-column
        prop="detailUrl"
        label="企业认证详情图"
      >
        <template slot-scope="scope">
          <el-image
            style="width: 100px; height: 100px"
            :src="scope.row.detailUrl"
            fit="contain"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="maxSelectCount"
        label="每人可查询次数"
      />
      <el-table-column
        prop="registAgreement"
        label="注册协议"
      />
      <el-table-column
        prop="serviceAgreement"
        label="服务协议"
      />
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :title="title" :visible.sync="dialogForm" width="40%" @opened="dialogOpen()" @close="colse">
      <el-form ref="form" :model="form" size="mini" :rules="rules">
        <el-form-item label="认证码" :label-width="formLabelWidth" prop="authCode">
          <el-input v-model="form.authCode" placeholder="请输入认证码" />
        </el-form-item>
        <el-form-item label="企业认证详情图" :label-width="formLabelWidth" prop="detailUrl">
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          <el-upload
            :limit="1"
            :on-exceed="(files, fileList)=>handleExceed(files, fileList, 1)"
            class="avatar-uploader"
            :class="noneBtnDealImg ? 'disUoloadSty':''"
            action="https://www.xunyingcg.com/companyAuth/api/oss/uploadFileToOss"
            :file-list="fileList"
            style="padding:30px 0 ;"
            list-type="picture-card"
            :on-success="(res, file, fileList)=>handleAvatarSuccess(res, file, fileList,'img')"
            :on-preview="handlePictureCardPreview"
            :on-remove="(file,fileList)=>handleRemove(file,fileList,'img')">
            <i class="el-icon-plus" ></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="每人可查询次数" :label-width="formLabelWidth" prop="maxSelectCount">
          <el-input v-model="form.maxSelectCount" placeholder="请输入认证码" />
        </el-form-item>
        <el-form-item label="注册协议" :label-width="formLabelWidth" prop="registAgreement">
<!--          <vue-ueditor-wrap v-model="form.registAgreement" />-->
          <div id="content" />
        </el-form-item>
        <el-form-item label="服务协议" :label-width="formLabelWidth" prop="serviceAgreement">
<!--          <vue-ueditor-wrap v-model="form.serviceAgreement" />-->
          <div id="content1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogForm = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
      <el-dialog :visible.sync="dialogVisible" append-to-body>
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { getCompanyAuth, companyAuthRemove, saveBanner } from '@/api/admin/companyAuth'
import VueUeditorWrap from 'vue-ueditor-wrap'
import E from 'wangeditor'

export default {
  components: {
    VueUeditorWrap
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      list: null,
      listLoading: true,
      dialogForm: false,
      dialogImageUrl: '',
      dialogVisible: false,
      noneBtnDealImg: false,
      form: {
        authCode: '',
        detailUrl: '',
        maxSelectCount: '',
        registAgreement: '',
        serviceAgreement: ''
      },
      fileList: [],
      rules: {
        authCode: [
          { required: true, message: '请输入认证码', trigger: 'blur' }
        ],
        detailUrl: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ],
        maxSelectCount: [
          { required: true, message: '请输入每人可查询次数', trigger: 'blur' }
        ],
        registAgreement: [
          { required: true, message: '请输入注册协议', trigger: 'blur' }
        ],
        serviceAgreement: [
          { required: true, message: '请输入服务协议', trigger: 'blur' }
        ]
      },
      title: '',
      formLabelWidth: '120px',
      optionProps: {
        value: 'id',
        label: 'name',
        children: 'children',
        checkStrictly: true
      },
      fileDialog: false,
      fileType: 'image',
      editor: null,
      editorDialog: false,
      editorFileType: 'image',
      editor1: null,
      editorDialog1: false,
      editorFileType1: 'image'
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleExceed(files, fileList, num) {
      this.$message.warning(`当前限制选择 ${num} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleRemove(file, fileList, name) {
      this.form.detailUrl = ''
      this.noneBtnDealImg = fileList.length >= 1
    },
    dialogOpen() {
      this.dialogOpened()
      this.dialogOpened1()
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    dialogOpened() {
      const that = this
      // 扩展菜单
      const { BtnMenu } = E
      class upimg extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(`<div class="w-e-menu" data-title="上传图片"><el-button>图片</el-button></div>`)
          super($elem, editor)
        }
        clickHandler() {
          that.editorFileType = 'image'
          that.editorDialog = true
        }
        tryChangeActive() {}
      }
      class upfile extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(`<div class="w-e-menu" data-title="上传附件"><el-button>附件</el-button></div>`)
          super($elem, editor)
        }
        clickHandler() {
          that.editorFileType = 'word'
          that.editorDialog = true
        }
        tryChangeActive() {}
      }
      class upvideo extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(`<div class="w-e-menu" data-title="上传视频"><el-button>视频</el-button></div>`)
          super($elem, editor)
        }
        clickHandler() {
          that.editorFileType = 'video'
          that.editorDialog = true
        }
        tryChangeActive() {}
      }
      class clear extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(`<div class="w-e-menu" data-title="清空内容"><el-button>清空</el-button></div>`)
          super($elem, editor)
        }
        clickHandler() {
          that.editor.txt.clear()
        }
        tryChangeActive() {}
      }
      that.editor = new E('#content')
      that.editor.config.showLinkImg = false; //隐藏‘网络图片’的按钮
      that.editor.config.uploadImgServer = 'https://www.xunyingcg.com/companyAuth/api/oss/uploadFileToOss' // 上传图片到服务器
      that.editor.config.uploadImgMaxSize = 2 * 1024 * 1024; // 将图片大小限制为 2M
      that.editor.config.uploadImgMaxLength = 5 // 限制一次最多上传 5 张图片
      that.editor.config.uploadFileName = 'file'
      that.editor.config.uploadImgTimeout = 30000 // 将 timeout 时间改为 3s
      that.editor.config.menus = [
        'bold',
        'italic',
        'underline',
        'strikeThrough',
        'link', // 插入链接
        'list', // 列表
        'quote', // 引用
        'image', // 插入图片
        'undo', // 撤销
        'redo' // 重复
      ]
      that.editor.config.uploadImgHooks = {
        customInsert: function(insertImgFn, result) {
          // result 即服务端返回的接口
          console.log('customInsert', result)

          // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
          insertImgFn(result.data)
        }
      }
      that.editor.config.height = 500
      that.editor.config.focus = false
      that.editor.config.placeholder = ''
      that.editor.config.onchange = (newHtml) => {
        that.form.registAgreement = newHtml
      }
      that.editor.create()
      that.editor.txt.html(that.form.registAgreement)
    },
    dialogOpened1() {
      const that = this
      // 扩展菜单
      const { BtnMenu } = E
      class upimg extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(`<div class="w-e-menu" data-title="上传图片"><el-button>图片</el-button></div>`)
          super($elem, editor)
        }
        clickHandler() {
          that.editorFileType = 'image'
          that.editorDialog = true
        }
        tryChangeActive() {}
      }
      class upfile extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(`<div class="w-e-menu" data-title="上传附件"><el-button>附件</el-button></div>`)
          super($elem, editor)
        }
        clickHandler() {
          that.editorFileType = 'word'
          that.editorDialog = true
        }
        tryChangeActive() {}
      }
      class upvideo extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(`<div class="w-e-menu" data-title="上传视频"><el-button>视频</el-button></div>`)
          super($elem, editor)
        }
        clickHandler() {
          that.editorFileType = 'video'
          that.editorDialog = true
        }
        tryChangeActive() {}
      }
      class clear extends BtnMenu {
        constructor(editor) {
          const $elem = E.$(`<div class="w-e-menu" data-title="清空内容"><el-button>清空</el-button></div>`)
          super($elem, editor)
        }
        clickHandler() {
          that.editor1.txt.clear()
        }
        tryChangeActive() {}
      }
      that.editor1 = new E('#content1')
      that.editor1.config.showLinkImg = false; //隐藏‘网络图片’的按钮
      that.editor1.config.uploadImgServer = 'https://www.xunyingcg.com/companyAuth/api/oss/uploadFileToOss' // 上传图片到服务器
      that.editor1.config.uploadImgMaxSize = 2 * 1024 * 1024; // 将图片大小限制为 2M
      that.editor1.config.uploadImgMaxLength = 5 // 限制一次最多上传 5 张图片
      that.editor1.config.uploadFileName = 'file'
      that.editor1.config.uploadImgTimeout = 30000 // 将 timeout 时间改为 3s
      that.editor1.config.menus = [
        'head',
        'bold',
        'fontSize',
        'fontName',
        'italic',
        'underline',
        'strikeThrough',
        'indent',
        'lineHeight',
        'foreColor',
        'backColor',
        'link',
        'list',
        'todo',
        'justify',
        'quote',
        'emoticon',
        'image',
        'video',
        'table',
        'code',
        'splitLine',
        'undo',
        'redo',
      ]
      that.editor1.config.uploadImgHooks = {
        customInsert: function(insertImgFn, result) {
          // result 即服务端返回的接口
          console.log('customInsert', result)

          // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
          insertImgFn(result.data)
        }
      }
      that.editor1.config.height = 500
      that.editor1.config.focus = false
      that.editor1.config.placeholder = ''
      that.editor1.config.onchange = (newHtml) => {
        that.form.serviceAgreement = newHtml
      }
      that.editor1.create()
      that.editor1.txt.html(that.form.serviceAgreement)
    },
    handleAvatarSuccess(response, file, fileList, name) {
      this.form.detailUrl = response.data
      this.fileList = []
      this.fileList = fileList
      this.noneBtnDealImg = fileList.length >= 1
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif' ||
        file
          .type === 'image/webp'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片JPG或者PNG格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    colse() {
      this.fileList = []
      this.editor.destroy()
      this.editor = null
      this.editor1.destroy()
      this.editor1 = null
      this.fileList = []
      this.form = {
        authCode: '',
        detailUrl: '',
        maxSelectCount: '',
        registAgreement: '',
        serviceAgreement: ''
      }
    },
    handleAdd() {
      this.dialogForm = true
      this.title = '新增企业认证配置'
    },
    handleEdit(index, row) {
      this.dialogForm = true
      this.form = JSON.parse(JSON.stringify(row))
      setTimeout(() => {
        this.fileList.push({ name: '', url: this.form.detailUrl })
      }, 500)
      this.title = '修改企业认证配置'
    },
    submit() {
      this.$refs.form.validate((vaild, done) => {
        if (vaild) {
          saveBanner(this.form).then(response => {
            this.getList()
            this.dialogForm = false
            this.form = {
              authCode: '',
              detailUrl: '',
              maxSelectCount: '',
              registAgreement: '',
              serviceAgreement: ''
            }
            this.$message({
              showClose: true,
              message: response.message,
              type: 'success'
            })
          })
        }
      })
    },
    handleDelete(index, row) {
      this.$confirm(
        '删除',
        '删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          companyAuthRemove(row.id).then(response => {
            this.getList()
            this.$message({
              showClose: true,
              message: response.message,
              type: 'success'
            })
          })
        })
    },
    getList() {
      this.listLoading = true
      getCompanyAuth().then(response => {
        this.list = response.data
        this.listLoading = false
      })
    }
  }
}
</script>

<style>
/deep/.el-form-item{
  margin-bottom: 0 !important;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style scoped>
.title{
  padding-left: 7px;
  font-size: 16px;
  font-weight: 500;
  line-height: 24px;
}
.right{
  display: flex;
  justify-content: flex-end;
}
.padding{
  margin-bottom: 20px;
}
.titles{
  display: flex;
  align-items: center;
}
.flex{
  padding-top: 20px;
}
</style>
